/**
 * 
 */
package cn.bigcontainer.alt.meta.dto;

import cn.bigcontainer.alt.common.entity.BigMap;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.meta.extension.MFormLoader;
import cn.bigcontainer.alt.meta.extension.MListLoader;
import cn.bigcontainer.alt.meta.po.MApp;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cailei
 * @date 2017年6月12日
 */
@Slf4j
public class MCrud extends MForm {

	public static final String SELECTOR_SINGLE = "single";

	public static final String SELECTOR_MULTIPLE = "multiple";

	public static final String TYPE_SEARCH = "search";

	/**
	 * crud的查询视图
	 */
	public static final String PARAM_SEARCH = PREFIX_VIEW + TYPE_SEARCH;

	public static final String TYPE_LIST = "list";

	/**
	 * crud的列表视图
	 */
	public static final String PARAM_LIST = PREFIX_VIEW + TYPE_LIST;

	public final static String PARAM_EXT_LIST_LOAD = PREFIX_EXTENSION + PARAM_LIST + ".load";

	/**
	 * 是否selector，前端提交过来的数据，仅放在内存中，不序列化到数据库
	 */
	private Boolean selector = false;

	/**
	 * 如果是selector，是否单选，前端提交过来的数据，仅放在内存中，不序列化到数据库
	 */
	private Boolean selectorsingle = true;

	public MCrud(MApp app) {
		super(app);
	}

	public MCrud(MApp app, BigMap<String, Object> req) {
		super(app, req);
	}

	public MCrud() {
		super();
	}

	public void setSearchView(MViewDto searchView) {
		setView(TYPE_SEARCH, searchView);
	}

	/**
	 * @return
	 */
	public String getSearchId() {
		return getViewId(TYPE_SEARCH);
	}

	/**
	 * @return
	 */
	public MViewDto getSearchView() {
		return getView(TYPE_SEARCH, "查询");
	}

	public void setListView(MViewDto listView) {
		setView(TYPE_LIST, listView);
	}

	/**
	 * @return
	 */
	public String getListId() {
		return getViewId(TYPE_LIST);
	}

	/**
	 * @return
	 */
	public MViewDto getListView() {
		return getView(TYPE_LIST, "列表");
	}

	public Boolean getSelector() {
		return selector;
	}

	public void setSelector(Boolean selector) {
		this.selector = selector;
	}

	public Boolean getSelectorsingle() {
		return selectorsingle;
	}

	public void setSelectorsingle(Boolean selectorsingle) {
		this.selectorsingle = selectorsingle;
	}

	private MListLoader listLoader = null;

	/**
	 *
	 * @return
	 */
	private MListLoader getExtensionListLoader () {
		if (listLoader != null) {
			return listLoader;
		}
		String ex = getExtension(PARAM_EXT_LIST_LOAD);
		if (WoKit.isEmpty(ex)) {
			return null;
		}
		if (WoKit.containsBean(ex)) {
			return listLoader = WoKit.getBean(MListLoader.class, ex);
		}
		return null;
	}

	/**
	 *
	 * @param list
	 * @param search
	 * @return
	 */
	public MViewDto beforeLoadList (MViewDto list, MViewDto search) {
		MListLoader ex = getExtensionListLoader();
		if (ex != null) {
			return ex.before(list, search);
		}
		return null;
	}

	/**
	 *
	 * @param list
	 * @param search
	 */
	public void afterLoadList (MViewDto list, MViewDto search) {
		MListLoader ex = getExtensionListLoader();
		if (ex != null) {
			ex.after(list, search);
		}
	}
}
